package com.ks.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//@WebFilter("/*")
public class CharasetFilter implements Filter {
	private FilterConfig config;
	private static final Logger LOGGER = LoggerFactory.getLogger(CharasetFilter.class);

	public void destroy() {
		LOGGER.debug("【{}】被销毁", this.getClass().getName());
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		String encoding = config.getInitParameter("encoding");
		LOGGER.trace("获取编码格式初始值【{}】", encoding);
		// 前驱操作 设置Request编码(注意这里是ServletRequest而并不是HttpServletRequest)
		request.setCharacterEncoding(encoding);
		response.setCharacterEncoding(encoding);
//		response.setContentType("text/html;charset=UTF-8");
		chain.doFilter(request, response);// 放行。让其走到下个链或目标资源中
		// 服务完后的代码....
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		LOGGER.debug("【{}】初始化", this.getClass().getName());
		config = fConfig;
	}

}
